package com.qf.controller;


import com.github.pagehelper.PageInfo;
import com.qf.entity.*;
import com.qf.enums.OAExceptionEnum;
import com.qf.service.AnnounceService;
import com.qf.service.TaskService;
import com.qf.service.TaskTypeService;
import com.qf.service.UserService;
import com.qf.utils.GzwUtil;
import com.qf.utils.GzwUtil1;
import com.qf.utils.NumberUtil;
import com.qf.utils.R;
import com.qf.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;


@Controller
@Slf4j
public class MyselfController {

    @Autowired
    private AnnounceService announceService;
    @Autowired
    private UserService userService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private TaskTypeService taskTypeService;

    //跳转到待审核处理页面
    @RequestMapping("/resource/myself/demo1/list")
    public String demo1List(@RequestParam(defaultValue = "1") Integer pageNum,
                            @RequestParam(defaultValue = "5") Integer size,
                            @RequestParam(defaultValue = "") String startTime,
                            @RequestParam(defaultValue = "") String endTime,
                            @RequestParam(defaultValue = "-1") Integer taskId,
                            Model model){
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        PageInfo<Task> pageInfo =taskService.findByUserId(user.getUserId(),pageNum,size,startTime,endTime,taskId);
        List<TaskType> taskTypeList = taskTypeService.findAllInfo();
        model.addAttribute("pageInfo",pageInfo);
        model.addAttribute("taskTypeList",taskTypeList);
        model.addAttribute("startTime",startTime);
        model.addAttribute("endTime",endTime);
        model.addAttribute("taskId",taskId);
        return "resource/myself/demo1/list";
    }

    //更新用户的申请状态
    /*/task/update/status?id=${task.id}&status=1*/
    @RequestMapping("/task/update/status")
    public String updateStatus(Integer id,Integer status,
                               @RequestParam(defaultValue = "1") Integer pageNum,
                               @RequestParam(defaultValue = "5") Integer size,
                               @RequestParam(defaultValue = "") String startTime,
                               @RequestParam(defaultValue = "") String endTime,
                               @RequestParam(defaultValue = "-1") Integer taskId,
                               Model model){
        taskService.updateStatus(id,status);
        return this.demo1List(pageNum,size,startTime,endTime,taskId,model);
    }

    //查看通知列表
    @RequestMapping("/resource/myself/demo2/list")
    public String demo2List(@RequestParam(defaultValue = "1") Integer pageNum,
                            @RequestParam(defaultValue = "5") Integer size,
                            @RequestParam(defaultValue ="") String annName,
                            @RequestParam(defaultValue ="")  String startTimes,
                            @RequestParam(defaultValue ="") String endTimes,
                            Model model){
       PageInfo<Annunciate> pageInfo =announceService.findAllInfoByStatus(pageNum,size,annName,startTimes,endTimes);
       model.addAttribute("pageInfo",pageInfo);
       model.addAttribute("annName",annName);
       model.addAttribute("startTimes",startTimes);
       model.addAttribute("endTimes",endTimes);
       return "resource/myself/demo2/list";
    }

    //查看详情
    @RequestMapping("/annunciate/look")
    public String looks(Integer anId,Model model){
        Annunciate annunciate=announceService.findInfoByAnId(anId);
        model.addAttribute("annunciate",annunciate);
        return "resource/myself/demo2/look";
    }

    //导出表单
    @RequestMapping("/excel/export")
    public void export(Integer[] anIds,HttpServletResponse response){
        ServletOutputStream outputStream=null;

        try {
            outputStream = response.getOutputStream();
            List<Annunciate> excle = announceService.getExcle(anIds);

            //生成随机名字
            String number = NumberUtil.getNumber(6);
            //设置导出格式
            response.setContentType("application/x-download");
            String excleName = "excle_"+number+ ".xls";
            response.addHeader("Content-Disposition", "attachment;filename=" + excleName);
            //设置表名
            GzwUtil.createFirstRow("用户信息");
            //设置类容
            GzwUtil.createSheetValue(excle);
            GzwUtil.export(outputStream);
            response.getWriter().print("<script>alert('导出成功');window.history.back();</script>");
            return;
        } catch (IOException e) {
            try {
                response.getWriter().print("<script>alert('失败');window.history.back();</script>");
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
        } finally {
            try {
                outputStream.flush();
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    //跳转到修改密码页面
    @RequestMapping("/resource/myself/demo3/list")
    public String demo3List(){
       return "resource/myself/demo3/list";
    }

    //修改密码
    @RequestMapping("/updated/password")
    @ResponseBody
    public ResultVO demo3Index(String username, String oldPassword, String newPassword){
        if(StringUtils.isEmpty(username)){
            log.error("【修改用户密码】参数不合法,username={}",username);
            return  R.error(OAExceptionEnum.USER_PARAM_ERROR.getCode(),"用户名不能为空");
        }
        if(StringUtils.isEmpty(oldPassword)){
            log.error("【修改用户密码】参数不合法,oldPassword={}",oldPassword);
            return  R.error(OAExceptionEnum.USER_PARAM_ERROR.getCode(),"旧密码不能为空");
        }
        if(StringUtils.isEmpty(newPassword)){
            log.error("【修改用户密码】参数不合法,newPassword={}",newPassword);
            return  R.error(OAExceptionEnum.USER_PARAM_ERROR.getCode(),"新密码不能为空");
        }
        //根据用户名修改用户信息
        userService.updateUserPassword(username,oldPassword,newPassword);
        return R.ok();
    }

    //跳转到我的申请详情页面
    @RequestMapping("/resource/myself/demo4/list")
    public String demo4List(@RequestParam(defaultValue = "1") Integer pageNum,
                            @RequestParam(defaultValue = "5") Integer size,
                            @RequestParam(defaultValue = "") String startTime,
                            @RequestParam(defaultValue = "") String endTime,
                            @RequestParam(defaultValue = "-1") Integer taskId,
                            Model model){
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        PageInfo<Task> pageInfo =taskService.findByUsername(user.getRealName(),pageNum,size,startTime,endTime,taskId);
        List<TaskType> taskTypeList = taskTypeService.findAllInfo();
        model.addAttribute("pageInfo",pageInfo);
        model.addAttribute("taskTypeList",taskTypeList);
        model.addAttribute("startTime",startTime);
        model.addAttribute("endTime",endTime);
        model.addAttribute("taskId",taskId);
        return "resource/myself/demo4/list";
    }
    //导出我的申请详情页
    @RequestMapping("/sys/deletes")
    public void deletes(Integer[] ids, HttpServletResponse response,String method){
        ServletOutputStream outputStream=null;
        response.setContentType("text/html;charset=utf-8");
        try {
            if(StringUtils.isEmpty(ids)){
                response.getWriter().print("<script>alert('请选择数据');window.history.back();</script>");
            }
            if(method.equals("exports")){
                try {
                    outputStream = response.getOutputStream();
                    List<Task> excle = taskService.getExcle(ids);

                    //生成随机名字
                    String number = NumberUtil.getNumber(6);
                    //设置导出格式
                    response.setContentType("application/x-download");
                    String excleName = "excle_"+number+ ".xls";
                    response.addHeader("Content-Disposition", "attachment;filename=" + excleName);
                    //设置表名
                    GzwUtil1.createFirstRow("个人申请信息");
                    //设置类容
                    GzwUtil1.createSheetValue(excle);
                    GzwUtil1.export(outputStream);
                    return;
                } catch (IOException e) {
                    try {
                        response.getWriter().print("<script>alert('失败');window.history.back();</script>");
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                    e.printStackTrace();
                } finally {
                    try {
                        outputStream.flush();
                        outputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }else if(method.equals("delete")) {
                List<Task> taskList= taskService.findByIds(ids);
                for (Task task : taskList) {
                    if(task.getStatus()==0){
                        log.error("【删除我的申请】删除我的申请失败");
                        response.getWriter().print("<script>alert('当前所选数据信息中的状态有：待审核状态，不能删除');location.href='/resource/myself/demo4/list'</script>");
                        return;
                    }
                }
                int count = taskService.deletes(ids);
                if(count>0){
                   response.getWriter().print("<script>alert('删除成功');location.href='/resource/myself/demo4/list'</script>");
                }else{
                    response.getWriter().print("<script>alert('删除失败');location.href='/resource/myself/demo4/list'</script>");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    //查看申请详情
    @RequestMapping("/task/look/detail")
    public String detail(Integer taskId,Integer eventId,Model model){
        Map<String,Object> map= taskService.detail(taskId,eventId);
        if(taskId==1){
                Leave leave  = (Leave) map.get("leave");
                model.addAttribute("leave",leave);
                 return "resource/myself/demo4/look";
          }else if(taskId==2){
                Business business = (Business) map.get("business");
                model.addAttribute("business",business);
                return "resource/myself/demo4/look1";
          }else if(taskId==3){
            ReserveCar reserveCar = (ReserveCar) map.get("reserveCar");
            model.addAttribute("reserveCar",reserveCar);
            return "resource/myself/demo4/look2";
          }else if(taskId==4){
              Seal seal = (Seal) map.get("seal");
              model.addAttribute("seal",seal);
              return "resource/myself/demo4/look3";
          }else if(taskId==5){
            Card card = (Card) map.get("card");
            model.addAttribute("card",card);
            return "resource/myself/demo4/look4";
          }else if(taskId==6){
            Income income = (Income) map.get("income");
            model.addAttribute("income",income);
            return "resource/myself/demo4/look5";
          }else if(taskId==7){
              ReserveMeet reserveMeet = (ReserveMeet) map.get("reserveMeet");
              model.addAttribute("reserveMeet",reserveMeet);
              return "resource/myself/demo4/look6";
          }
      return null;
    }
}
